/*
 * SwingTextValueEditor.java - Copyright Apr 27, 2012 Z Networks Group, Inc. All rights reserved.
 * Z Networks Group PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.andromeda.skadi.sandbox2;

import com.andromeda.skadi.view.swing.listener.SkadiDocumentListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 *
 * @author Dickinson Roman Arismendy Torres
 */
public class SwingTextValueEditor extends AbstractValueEditor<String> implements SwingValueEditor<String>, ActionListener {

    private JTextField delegate;
    private Timer timer;
    private int delay = 800;

    public SwingTextValueEditor() {
        delegate = new JTextField();
        delegate.getDocument().addDocumentListener(new CustomDocumentListener());
        timer = new Timer(delay, this);
        timer.setRepeats(true);
    }

    private void onValueChanged() {

        if (timer.isRunning()) {
            timer.restart();
        } else {
            timer.start();
        }
    }

    @Override
    public void setValue(String value) {
        delegate.setText(value);
    }

    @Override
    public String getValue() {
        return delegate.getText();
    }

    @Override
    public Class<String> getRenderedType() {
        return String.class;
    }

    @Override
    public JComponent getComponent() {
        return delegate;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        fireValueChanged();
        timer.stop();
    }

    private class CustomDocumentListener implements DocumentListener {

        @Override
        public void insertUpdate(DocumentEvent e) {
            onValueChanged();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            onValueChanged();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            onValueChanged();
        }
    }
}
